package com.tianxu.hadoop.hdfs;

import com.tianxu.hadoop.utils.FileSystemUtil;
import org.apache.commons.lang3.builder.ToStringExclude;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.junit.Test;
import sun.lwawt.macosx.CSystemTray;

import java.io.File;
import java.io.FileOutputStream;

public class HDFSClient {
    //1.获取FileSystem对象（获取HDFS对象）
    FileSystem hdfs = FileSystemUtil.getFS();

    /**
     * 创建文件的方法 create
     */
    @Test
    public void create() throws Exception {
        //向根目录下写入一个f.txt
        Path path = new Path("/f.txt");
        FSDataOutputStream out = hdfs.create(path);
        out.write("Hadoop Spark Linux \n".getBytes());
        out.write("Java MySQL HBase \n".getBytes());
        out.flush();//清空内存
        out.close();//关闭文件
    }

    /**
     * 查看读取HDFS文件上的内容，把内容打印到控制台
     * @throws Exception
     */
    @Test
    public void open() throws Exception {
        FSDataInputStream in = hdfs.open(new Path("/f.txt"));
        IOUtils.copyBytes(in,System.out,1024);

        in.close();

        //System.out.println();
    }

    /**
     * 把内容写到本地的文件中
     * @throws Exception
     */
    @Test

    public void openToFile() throws Exception{
        FSDataInputStream in = hdfs.open(new Path("/f.txt"));
        FileOutputStream out = new FileOutputStream(new File("file/c.txt"));
        IOUtils.copyBytes(in,out,1024);
        in.close();
        out.close();
    }
    /**
     * 删除文件
     *
     */
    @Test
    public void delete() throws Exception{
        boolean delete = hdfs.delete(new Path("/one"),true);
        System.out.println("目录或文件删除成功？："+delete);
    }
    /**
     * 向hdfs文件中追加内容
     * 方法：append()
     */

    @Test

    public void append() throws Exception{
        FSDataOutputStream append = hdfs.append(new Path("/e.txt"));
        //append.write("这是新增加的内容 \n".getBytes());
        append.writeUTF("这是新增加的内容 \n");
        append.flush();
        append.close();
    }



    /**
     * 上传
     * @throws Exception
     */
    @Test
     public void copyFromLocal() throws Exception{
        hdfs.copyFromLocalFile(new Path("file/c.txt"),new Path("/a/c.txt"));
         System.out.println("文件上传成功！");
     }

    /**
     *下载
     * @throws Exception
     */
     @Test
    public void copyToLocal() throws  Exception{
        hdfs.copyToLocalFile(new Path("/a/c.txt"),new Path("file/a.txt"));
         System.out.println("文件下载成功！");
     }

    /**
     *重命名文件和目录，不能跨文件系统
     * @throws Exception
     */
    @Test
    public void rename() throws Exception{
        boolean rename = hdfs.rename(new Path("/a.txt"), new Path("/test.txt"));
        System.out.println("修改成功了吗？" + rename);
     }

}